<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/controller/ctlAbstract.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

class ActivateController extends AbstractController {
	private $_userBus;
	
	public function __construct(){
		$this->_userBus = new UserBus();
	}
	
	/**
	 * 
	 * This function will verify the activation code of user
	 * If the activation code is valide, the user will be activated
	 * @param $code the activation code
	 */
	public function main(array $getVars) {
		//if there is code passed in the url
		if (isset($getVars['code'])) {
			//get the code
			$code = $getVars['code'];
			
			//operate the code
			$this->operateCode($code);
			
		} else {  //if there is not code in the url
			//check if the code is posted
			if (isset($_POST['txtCode'])) {
				$code = $_POST['txtCode'];
				
				$this->operateCode($code);
			} else {
				//display the form to enter code
				require_once $ubi['SERVER']['SERVER_ROOT'] . 'view/viewActivate.php';
			}
		}
	}
	
	protected function validateCode($code) {
		return (strlen($code) == 20);			
	}
	
	protected function operateCode($code) {
		global $ubi;
		$notice = "";
		//validate the code
		if ($this->validateCode($code)){
			//activate user
			//if successfully, display notice
			$result = $this->_userBus->activateUser($code);
			if ($result > 0) {
				//try to send email
				//get user record
				$user = $this->_userBus->getUser($result);
				if ($user) { //got the user				
					$subject = 'Chúc mừng ' . $user->getFirstName() . ' ' . $user->getLastName()
					 			. '! Tài khoản của bạn đã được kích hoạt!';
					$message = "Xin chào " . $user->getFirstName() . ' ' . $user->getLastName() . ".<br />\n"
							. 'Chúc mừng bạn. Tài khoản của bạn tại <a href ="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a> đã được kích hoạt thành công!';

					if (GeneralFunctions::ubiMail($user->getEmail(), $subject, $message)) {
						$notice = "ActivateSuccessfully";
					} else {
						$notice = "ActivateSuccessfullyButCannotSendMail";
					}
				}
				else {//can't get user -> can't send mail				
					$notice = "ActivateSuccessfullyButCannotSendMail";
				}
			}
			else if ($result == 0) {
				//display invalid code
				$notice = "ActivateWithInvalidCode";
			} else if ($result == -1) {
				$notice = "ActivateUserAlreadyActivated";
			}			
		} else {
			//display notice that the code is not valid
			$notice = "ActivateWithInvalidCode";
		}
		require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
	}
}
?>